package org.kymjs.emoji;

import java.util.ArrayList;
import java.util.List;

import org.kymjs.emoji.control.EmojiGridAdapter;
import org.kymjs.emoji.model.DisplayRules;
import org.kymjs.emoji.model.EmojiIcon;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

/**
 * 表情页，每页的显示
 * 
 * @author kymjs
 * 
 */
public class EmojiPageFragment extends Fragment {
    private final List<EmojiIcon> datas;
    private GridView mGrid;

    public EmojiPageFragment(int index, int type) {
        datas = new ArrayList<EmojiIcon>();
        List<EmojiIcon> dataAll = DisplayRules.getAllByType(type);
        int max = Math.min((index + 1) * KJEmojiFragment.COUNT_IN_PAGE,
                dataAll.size());
        for (int i = index * KJEmojiFragment.COUNT_IN_PAGE; i < max; i++) {
            datas.add(dataAll.get(i));
        }
        datas.add(new EmojiIcon(R.drawable.ic_launcher, 1, "delete:"));
    }

    @Override
    public View onCreateView(LayoutInflater inflater,
            @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        mGrid = new GridView(getActivity());
        mGrid.setNumColumns(KJEmojiFragment.COLUMNS);
        mGrid.setAdapter(new EmojiGridAdapter(getActivity(), datas));
        mGrid.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                FragmentActivity aty = getActivity();
                if (aty instanceof EmojiClickListener) {
                    if (position + 1 != datas.size()) {
                        ((EmojiClickListener) aty)
                                .onEmojiClick((EmojiIcon) parent.getAdapter()
                                        .getItem(position));
                    } else {
                        ((EmojiClickListener) aty).onDeleteClick();
                    }
                } else {
                    Log.e("KJEmoji",
                            "Activity must implements EmojiClickListener");
                }
            }
        });
        return mGrid;
    }
}
